package util

import (
	"encoding/json"
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"log"
	"net/http"
	"userrpc/internal/models"
)

const url = "https://eid.shumaidata.com/eid/check"

func MonthAuths(name, idCard string) (string, error) {
	client := &http.Client{}
	data := url + "?idcard=" + idCard + "&name=" + name
	req, err := http.NewRequest("POST", data, nil)
	if err != nil {
		log.Println("客户端实例化失败", err)
		return "", errors.New("客户端实例化失败")
	}
	req.Header.Set("Authorization", "APPCODE 986a3f5395ca460cafc452139c7123cf")
	resp, err := client.Do(req)
	if err != nil {
		log.Println("客户端发送请求失败", err)
		return "", errors.New("客户端发送请求失败")
	}
	defer resp.Body.Close()
	var m map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&m)
	if err != nil {
		log.Println("转换json失败", err)
		return "", errors.New("转换json失败")
	}
	r, ok := m["result"].(map[string]interface{})
	if !ok {
		return "", errors.New("未发现结果")
	}
	return r["description"].(string), nil
}
func SelAuth(username string) error {
	o := orm.NewOrm()
	s := models.User{}
	o.QueryTable("user").Filter("username", username).One(&s)
	if s.AuthCode != "" {
		return errors.New("账号已实名")
	}
	return nil
}
func SetAuth(username, name, idCard string) error {
	o := orm.NewOrm()
	s := models.User{}
	o.QueryTable("user").Filter("username", username).One(&s)
	s.Name = name
	s.AuthCode = idCard
	_, err := o.Update(&s)
	if err != nil {
		return errors.New("实名成功")
	}
	return nil
}
